from scenedetect import SceneManager, VideoManager
from scenedetect.detectors import ContentDetector
# from scenedetect.video_splitter import split_video_ffmpeg

from tool import time_diff

def find_video_scenes(video_path, threshold = 75, min_duration = 4):
    # 获取某一个视频分节的时间信息
    # Create our video & scene managers, then add the detector.
    video_manager = VideoManager([video_path])
    scene_manager = SceneManager()
    scene_manager.add_detector(ContentDetector(threshold))

    # Improve processing speed by downscaling before processing.
    video_manager.set_downscale_factor()

    # Start the video manager and perform the scene detection.
    video_manager.start()
    scene_manager.detect_scenes(frame_source=video_manager)

    # 保存为视频文件
    scene_list = scene_manager.get_scene_list()

    scenes_info = []

    # print('List of scenes obtained:')
    for scene in scene_list:
        if time_diff(scene[0].get_timecode(), scene[1].get_timecode()) > min_duration:
            scenes_info.append({
                "start": scene[0].get_timecode(),
                "end": scene[1].get_timecode(),
                'start_frame': scene[0].get_frames(),
                'end_frame': scene[1].get_frames()
            })

    video_manager.release()

    return scenes_info

def get_better_scenes_group(scenes_info, threshold_minitues=2.5):
    threshold_minitues = threshold_minitues * 60
    concat_arr = []
    l = len(scenes_info)
    i = 0
    group = []
    while i < l:
        if time_diff(scenes_info[i]["end"], scenes_info[i]["start"]) >= threshold_minitues:
            if len(group) > 0:
                concat_arr.append(group)
            concat_arr.append([i])
            group = []
            i += 1
            continue

        group.append(i)

        if i == l - 1:
            concat_arr.append(group)
        elif time_diff(scenes_info[group[0]]["start"], scenes_info[group[len(group) - 1]]["end"]) >= threshold_minitues:
            concat_arr.append(group)
            group = []
        
        i += 1

    return concat_arr


if __name__ == "__main__":
    # print(find_video_scenes("./videos/test.mp4"))
    scenes_info = [{
        "start": "00:00:00.00",
        "end": "00:02:00.9",
        "start_frame": 1234,
        "end_frame":  4567
    }, {
         "start": "00:02:00.90",
        "end": "00:04:00.9",
        "start_frame": 1234,
        "end_frame":  4567
    },{
         "start": "00:04:00.9",
        "end": "00:08:00.9",
        "start_frame": 1234,
        "end_frame":  4567
    },{
         "start": "00:05:00.9",
        "end": "00:06:00.9",
        "start_frame": 1234,
        "end_frame":  4567
    }]

    print(get_better_scenes_group(scenes_info))

    